//
//  DesDetailController.m
//  MyTrip
//
//  Created by zhang on 15/8/29.
//  Copyright (c) 2015年 张益. All rights reserved.
//

#import "DesDetailController.h"
#import "AsyncGETConnection.h"
#import "HotDesCell.h"
#import <ShareSDK/ShareSDK.h>
#import "Destination.h"
#import "MJRefresh.h"
#import "UIImageView+WebCache.h"
#import "PhotoController.h"
#import "MBProgressHUD.h"
#import "UMSocial.h"
#define kImageOriginHight 220 * OffHeight
#define kTempHeight 20 * OffHeight


@interface DesDetailController ()<UICollectionViewDataSource, UICollectionViewDelegate, UMSocialUIDelegate>

@property (nonatomic, retain) UICollectionView *collection;
@property (nonatomic, retain) NSMutableArray *desArr;
@property (nonatomic, retain) NSNumber *startNum;
@property (nonatomic, retain) UIImageView *expandZoomImageView;
@property (nonatomic, retain) MBProgressHUD *hud;


@end

@implementation DesDetailController

- (void)dealloc
{
    [_desArr release];
    [_collection release];
    [super dealloc];
}


- (instancetype) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.desArr = [NSMutableArray array];
    }
    return self;
}

- (void)getMessage{
    
    self.hud = [[MBProgressHUD alloc] init];
    [self.view addSubview:_hud];
    [_hud show:YES];
    _hud.labelText = @"正在拼命加载......";
    //    在网络请求之后
    
    __block MBProgressHUD *hud = _hud;
    [AsyncGETConnection asyncGETConnectionWithURLStr:[NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%ld/%@/pois/all/?sort=default&start=0&latitude=38.883652&longitude=121.544418&sign=627cbf1782c299ad2b85f71461fd21b7", self.type, self.idNum] parameters:nil messageBlock:^(NSData *data) {
        hud.hidden = YES;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *items = [dic objectForKey:@"items"];
        self.startNum = [dic objectForKey:@"next_start"];
        [_desArr addObjectsFromArray:items];
        [_collection reloadData];
    }];

}

- (void)createCollection{
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width - (20 * OffWidth), (120 * OffHeight));
    
    self.collection = [[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - (64 * OffHeight)) collectionViewLayout:flowLayout] autorelease];
    self.collection.contentInset = UIEdgeInsetsMake(kImageOriginHight, 0, 0, 0);
    [_collection setBackgroundColor:[UIColor whiteColor]];
    _collection.delegate = self;
    _collection.dataSource = self;
    [_collection registerClass:[HotDesCell class] forCellWithReuseIdentifier:@"hot"];
    [self.view addSubview:_collection];
    
    
    self.expandZoomImageView = [[UIImageView alloc]init];
    [self.expandZoomImageView sd_setImageWithURL:[NSURL URLWithString:_destination.zoomImage]];
    self.expandZoomImageView.frame = CGRectMake(0, -kImageOriginHight - kTempHeight, self.collection.frame.size.width, kImageOriginHight + kTempHeight);
    
    [self.collection addSubview:self.expandZoomImageView];
    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat yOffset  = scrollView.contentOffset.y;
    NSLog(@"yOffset===%f",yOffset);
    CGFloat xOffset = (yOffset + kImageOriginHight)/2;
    if (yOffset < -kImageOriginHight) {
        CGRect f = self.expandZoomImageView.frame;
        f.origin.y = yOffset - kTempHeight;
        f.size.height =  -yOffset + kTempHeight;
        f.origin.x = xOffset;
        f.size.width = 375 * OffWidth + fabsf(xOffset) * 2;
        self.expandZoomImageView.frame = f;
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [_desArr count];
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HotDesCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"hot" forIndexPath:indexPath];
    NSDictionary *dic = [_desArr objectAtIndex:indexPath.item];
    
    [cell setValueWithDic:dic];
//    NSLog(@"%ld", indexPath.item);
    return cell;
}





- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dic = [_desArr objectAtIndex:indexPath.item];
    PhotoController *photo = [[PhotoController alloc] init];
    
    photo.type = [[dic objectForKey:@"type"] integerValue];
    photo.idNum = [[dic objectForKey:@"id"] integerValue];
    photo.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:70 / 255.0f green:160 / 255.0f blue:175 / 255.0f alpha:1];
    
    photo.navigationItem.title = [NSString stringWithFormat:@"%@ 图集", [dic objectForKey:@"name"]];
    [self.navigationController pushViewController:photo animated:YES];
    [photo release];
    
    
}

- (void)createRightButton{
    
    UIButton *button = [[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25 * OffWidth, 15 * OffHeight)] autorelease];
    [button setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"share" ofType:@"png"]] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    
}


- (void)shareAction:(UIButton *)sender{
    NSLog(@"share");
    
    NSLog(@"分享");
    
    
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"55f036aa67e58e5dd700440e" shareText:@"发现一个目的地，好像很不错啊，感兴趣的朋友一起吧" shareImage:nil shareToSnsNames:[NSArray arrayWithObjects:UMShareToRenren,UMShareToTencent, UMShareToSina, nil] delegate:self];
    
    
    
//    id<ISSContent> publishContent = [ShareSDK content:_destination.name
//                                       defaultContent:@"#目的地推荐#"
//                                                image:[ShareSDK imageWithPath:_destination.cover]
//                                                title:@"来旅行吧"
//                                                  url:[NSString stringWithFormat:@"http://web.breadtrip.com/scenic/%ld/%@/", self.type, self.idNum]
//                                          description:@"发现一个目的地，好像很不错啊，感兴趣的朋友一起吧"
//                                            mediaType:SSPublishContentMediaTypeNews];
//    //1+创建弹出菜单容器（iPad必要）
//    id<ISSContainer> container = [ShareSDK container];
//    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
//    
//    //2、弹出分享菜单
//    [ShareSDK showShareActionSheet:container
//                         shareList:nil
//                           content:publishContent
//                     statusBarTips:YES
//                       authOptions:nil
//                      shareOptions:nil
//                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
//                                
//                                //可以根据回调提示用户。
//                                if (state == SSResponseStateSuccess)
//                                {
//                                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享成功"
//                                                                                    message:nil
//                                                                                   delegate:self
//                                                                          cancelButtonTitle:@"OK"
//                                                                          otherButtonTitles:nil, nil];
//                                    [alert show];
//                                }
//                                else if (state == SSResponseStateFail)
//                                {
//                                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
//                                                                                    message:[NSString stringWithFormat:@"失败描述：%@",[error errorDescription]]
//                                                                                   delegate:self
//                                                                          cancelButtonTitle:@"OK"
//                                                                          otherButtonTitles:nil, nil];
//                                    [alert show];
//                                }
//                            }];
    
    
}





- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self createRightButton];
    [self createCollection];
    [self getMessage];
    
    
//    [_collection addHeaderWithCallback:^{
//        [AsyncGETConnection asyncGETConnectionWithURLStr:[NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%ld/%@/pois/all/?sort=default&start=0&latitude=38.883652&longitude=121.544418&sign=627cbf1782c299ad2b85f71461fd21b7", self.type, self.idNum] parameters:nil messageBlock:^(NSData *data) {
//            [_collection headerEndRefreshing];
//            [_desArr removeAllObjects];
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//            NSArray *items = [dic objectForKey:@"items"];
//            [_desArr addObjectsFromArray:items];
//            [_collection reloadData];
//        }];
//    }];
    
    [_collection addFooterWithCallback:^{
        _hud.hidden = NO;
        [AsyncGETConnection asyncGETConnectionWithURLStr:[NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%ld/%@/pois/all/?sort=default&start=%@&latitude=38.883652&longitude=121.544418&sign=627cbf1782c299ad2b85f71461fd21b7", self.type, self.idNum, self.startNum] parameters:nil messageBlock:^(NSData *data) {
            _hud.hidden = YES;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *items = [dic objectForKey:@"items"];
            self.startNum = [dic objectForKey:@"next_start"];
            [_desArr addObjectsFromArray:items];
            [_collection reloadData];
            [_collection footerEndRefreshing];
            
        }];
    }];
    
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
